<template>
<div class="full-container">
    <div class="edit-container">
        <div class="mail-settings">
                <div class="receive-settings">
                    <b-input placeholder="收件箱"
                        type="email"
                        icon="email"
                        v-model="replyMailAd"
                        class="input-item">
                    </b-input>
                    <b-checkbox>验证有效再发</b-checkbox>
                </div>
                <div class="receive-settings">
                    <b-input placeholder="请选择发件箱" disabled v-model="choosenMailBox"></b-input>
                    <a class="button is-info" @click="choseSendMialBox">选择发件箱</a>
                    <a class="button is-info" @click="sendMailMgr">发件箱管理</a>
                    <!-- <label>选择发件箱类型</label>
                    <b-select v-model="sendMailBoxType">
                        <option value="0">
                            qq邮箱
                        </option>
                        <option value="1">
                            腾讯企业邮
                        </option>
                    </b-select> -->
                    <label style="margin-left:10px;">发件间隔</label>
                    <b-select class="send-interval" placeholder="发件间隔" v-model="intervalSeconds">
                        <option value="20">
                            10~20秒
                        </option>
                        <option value="30">
                            20~30秒
                        </option>
                        <option value="40">
                            30~40秒
                        </option>
                        <option value="50">
                            40~50秒
                        </option>
                        <option value="60">
                            50~60秒
                        </option>
                    </b-select>
                    <label style="margin-left:10px;">休息时间</label>
                    <b-select class="send-interval" placeholder="休息时间" v-model="sleepInterval">
                        <option value="10">
                            0~10分钟
                        </option>
                        <option value="20">
                            10~20分钟
                        </option>
                        <option value="30">
                            20~30分钟
                        </option>
                        <option value="40">
                            30~40分钟
                        </option>
                        <option value="50">
                            40~50分钟
                        </option>
                        <option value="60">
                            50~60分钟
                        </option>
                    </b-select>
                    <label style="margin-left:10px;">发件数</label>
                    <b-input v-model="continuousMailCount" placeholder="发件数应当在100～500" style="margin-left:10px" />
                    <!-- <b-select class="send-interval" v-model="continuousMailCount">
                        <option value="50">
                            50封
                        </option>
                        <option value="100">
                            100封
                        </option>
                        <option value="200">
                            200封
                        </option>
                    </b-select> -->
                </div>
                <div class="receive-settings">
                    <label style="margin-right:10px;">选择发件客户分类</label>
                    <b-select
                        placeholder="客户分类"
                        expanded
                        v-model="currentCustomerType">
                        <option v-for="item in customerTypeList" :key="item.id" :value="item.id">{{item.name}}</option>
                    </b-select>
                    <a class="button is-info" @click="templateMgrActive=true">选择模板</a>
                  </div>
                <div class="receive-settings">
                  <a class="button is-info" @click="inputTmpNameActive=true">保存为新模板</a>
                  <a class="button is-info" @click="confirmUpdateMailTmp">保存已有模板</a>
                </div>
            </div>
            <hr class="is-medium">
            <b-field label="添加邮件标题">
                <!--<b-taginput-->
                    <!--v-model="mailTitleList"-->
                    <!--ellipsis-->
                    <!--icon="label"-->
                    <!--placeholder="回车添加邮件标题">-->
                <!--</b-taginput>-->
              <b-input placeholder="添加邮件标题"
                       icon="label"
                       v-model="mailTitle"
                       class="input-item"></b-input>
            </b-field>
            <hr class="is-medium">
            <b-field label="编辑邮件内容">
                <!-- <quill-editor
                    v-model="content"
                    class="mail-editor"
                    ref="myQuillEditor"
                    :options="editorOption" >
                </quill-editor> -->
                    <quill-editor v-model="content"
                            :options="editorOption">
                </quill-editor>
            </b-field>
            <b-field label="编辑邮件签名">
              <!-- <quill-editor
                  v-model="content"
                  class="mail-editor"
                  ref="myQuillEditor"
                  :options="editorOption" >
              </quill-editor> -->
              <quill-editor v-model="sign"
                            :options="editorOption">
              </quill-editor>
            </b-field>
            <hr class="is-medium">
            <div class="settings">
                <div class="settings-left">
                    <b-checkbox>紧急邮件</b-checkbox>
                    <b-checkbox>已读回执</b-checkbox>
                    <b-field class="file">
                        <!-- <b-upload v-model="file">
                            <a class="button is-primary">
                                <b-icon icon="upload"></b-icon>
                                <span>上传附件</span>
                            </a>
                        </b-upload> -->
                        <!-- <span class="file-name" v-if="file">
                            {{ file.name }}
                        </span> -->
                    </b-field>
                </div>
                <div>
                    <a class="button is-info" @click="sendEmail">发送邮件</a>
                </div>
            </div>
    </div>
    <!-- 选择发件箱modal -->
    <b-modal :active.sync="isCardModalActive" :width="640" scroll="keep">
        <div class="modal-table">
        <b-table
            :data="sendMailBoxList"
            class="customer-table"
            :striped="true"
            :narrowed="true"
            :paginated="true"
            :per-page="10">
            <template slot-scope="props">
              <b-table-column label="选择">
                <b-radio v-model="radio"
                    :native-value="props.row.id">
                    选择此邮箱
                </b-radio>
              </b-table-column>
            <b-table-column field="id" label="ID">
                {{props.row.id}}
              </b-table-column>
              <b-table-column field="sendMail" label="邮箱" email>
                {{ props.row.email }}
              </b-table-column>
            </template>
          </b-table>
            <a class="button is-info" @click="confirmOutMailBox">确定选择</a>
        </div>
    </b-modal>
    <b-modal :active.sync="isSendMailMgrActive" :width="640"  scroll="keep">
      <div class="edit-container">
        <div class="edit-button">
          <a class="button is-info" @click="isNewMailCardActive = true">新增发件箱</a>
        </div>
        <div class="customer-table">
          <b-table
            :data="sendMailBoxList"
            class="customer-table"
            :striped="true"
            :narrowed="true"
            :paginated="true"
            :per-page="15">
            <template slot-scope="props">
              <b-table-column field="id" label="序号" width="50" numeric>
                {{ props.row.id }}
              </b-table-column>
              <b-table-column field="email" label="邮箱" email>
                {{ props.row.email }}
              </b-table-column>
              <b-table-column field="createdAt" label="创建时间">
                {{props.row.createdAt}}
              </b-table-column>
              <b-table-column label="删除">
                <a class="button is-danger" @click="deleteSendMailBox(props.row.id)">删除</a>
              </b-table-column>
            </template>
          </b-table>
        </div>
      </div>
    </b-modal>
    <!-- 新增发件箱模态框 -->
    <b-modal :active.sync="isNewMailCardActive" :width="640" scroll="keep">
      <div class="edit-container">
        <div class="card">
          <div class="card-content">
            <b-field label="邮箱">
              <b-input v-model="email" type="email"></b-input>
            </b-field>
            <b-field label="邮箱密码">
              <b-input v-model="password" type="password"></b-input>
            </b-field>
            <b-field label="选择邮箱类型">
              <b-select v-model="sendBoxType" expanded>
                <option value="0">qq邮箱</option>
                <option value="1">腾讯企业邮</option>
              </b-select>
            </b-field>
            <div class="card-button">
              <a class="button is-info" @click="createNewMailBox">新建发件箱</a>
            </div>
          </div>
        </div>
      </div>
    </b-modal>
    <b-modal :active.sync="inputTmpNameActive" :width="640"  scroll="keep">
      <div class="modal-table">
      <b-field label="模板名称">
        <b-input v-model="tempName" type="text"></b-input>
      </b-field>
      <a class="button is-info" @click="confirmSaveMailTmp">确定保存</a>
      </div>
    </b-modal>
    <b-modal :active.sync="templateMgrActive" :width="640"  scroll="keep">
      <div class="edit-container">
        <div class="edit-button">
        </div>
        <div class="customer-table">
          <b-table
            :data="templateList"
            class="customer-table"
            :striped="true"
            :narrowed="true"
            :paginated="true"
            :per-page="15">
            <template slot-scope="props">
              <b-table-column label="选择">
                <b-checkbox
                  v-model="props.row.status"
                  value="accepted"
                  unchecked-value="not_accepted"
                ></b-checkbox>
              </b-table-column>
              <b-table-column field="id" label="序号" width="50" numeric>
                {{ props.row.id }}
              </b-table-column>
              <b-table-column field="tempName" label="模板名称" email>
                {{ props.row.tempName }}
              </b-table-column>
              <b-table-column field="createdAt" label="模板详情">
               <a class="button is-info" @click="openTmpDetail(props.row)">查看详情</a>
              </b-table-column>
              <b-table-column label="删除">
                <a class="button is-danger" @click="confirmDeleteMailTmp(props.row.id)">删除</a>
              </b-table-column>
            </template>
          </b-table>
        </div>
      </div>
    </b-modal>
    <b-modal :active.sync="templateDetailActive" :width="640"  scroll="keep">
      <div class="edit-container" id="tmpDetail">

      </div>
    </b-modal>
    <!-- loading -->
    <b-loading :is-full-page="isFullPage" :active.sync="isLoading" :can-cancel="false"></b-loading>
</div>
</template>
<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import { getUserId } from "@/util/userInfoStorage"
import {startMailTask} from "@/api/mailTask.js"
import { getAllUserMailBox, createUserMailBox, deleteUserMailBox } from "@/api/mail.js"
import { getCustomerTypeByUserId } from "@/api/customerType"
import { getAllTempUserId,updateMaiTemp,createMaiTemp,deleteUserMailTemp } from "@/api/mailTemplate"
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

export default {
    components: {
        quillEditor
    },
    data(){
        return {
            currentCustomerType: 0,
            customerTypeList: [],
            choosenMailBox: '',
            radio: 0,
            isCardModalActive: false,
            isSendMailMgrActive:false,
            isNewMailCardActive:false,
            inputTmpNameActive:false,
            templateMgrActive:false,
            templateDetailActive:false,
            mailTitleList: ['test'],
            sendMailBoxList: [],
            userId: 0,
            mailTitle: '',
            inboxMailAd: '',//收件箱
            replyMailAd: '', //回复地址
            intervalSeconds: 0, //间隔时间
            sleepInterval: 0, //休眠时间
            continuousMailCount: 0,//连续发件数
            content: '',
            sign:'',
            tempName:'',
            // editorOption: {
            //     placeholder: "请输入邮件内容",
            //     modules: {
            //         toolbar: ['bold', 'italic', 'underline', 'strike', 'link', 'image','underline','align']
            //     },
            // },
            editorOption: {
                modules: {
                    toolbar: [
                        [{ 'size': ['small', false, 'large'] }],
                        ['bold', 'italic'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        ['link', 'image']
                    ],
                    history: {
                        delay: 1000,
                        maxStack: 50,
                        userOnly: false
                    },
                    // imageResize: {
                    //     displayStyles: {
                    //         backgroundColor: 'black',
                    //         border: 'none',
                    //         color: 'white'
                    //     },
                    //     modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
                    // }
                }
            },
            file: null,
            isLoading: false,
            isFullPage: true,
            // sendMailBoxType: -1,
            email: '',
            password: '',
            sendBoxType: -1,
            templateList:[],
            currentTmpId:0,
        }
    },
    mounted() {
        let userId = getUserId();
        this.userId = userId;
        // this.getSendBoxList();
        this.getCustomerTypeList();
        this.getTempList();
    },
    watch: {
    },
    methods: {
        //点击加载发件箱数据
        choseSendMialBox(){
            this.getSendBoxList();
            this.isCardModalActive = true;
        },
        //点击加载发件箱数据
        sendMailMgr(){
          this.getSendBoxList();
          this.isSendMailMgrActive = true;
        },
        //获取客户分类
        getCustomerTypeList(){
            getCustomerTypeByUserId(this.userId).then((res) => {
                console.log(res)
                this.customerTypeList = res.data;
            }).catch((e) => {
                console.log(e.message);
            })
        },
        //获取模板列表
        getTempList(){
          getAllTempUserId(this.userId).then((res) => {
            console.log(res)
            this.templateList = res.data;
            for(var i=0;i<this.templateList.length;i++){
              if(!this.templateList[i].status){
                this.templateList[i].status="not_accepted"
              }
            }
          }).catch((e) => {
            console.log(e.message);
          })
        },
        //选择发件箱
        confirmOutMailBox(){
            for(let item of this.sendMailBoxList){
                if(this.radio == item.id){
                    this.choosenMailBox = item.email;
                    this.isCardModalActive = false;
                }
            }
        },
        //toast方法
        showToast(message,type){
            this.$toast.open({
                message: message,
                type: type
            })
        },
        //获取发件箱列表
        getSendBoxList() {
            this.isLoading = true;
            getAllUserMailBox(this.userId).then((res) => {
                this.sendMailBoxList = res.data;
                this.isLoading = false;
            }).catch(e => {
                this.isLoading = false;
                console.log(e);
            });
        },
        //发送邮件
        sendEmail(){
            //邮箱正则验证
            let emailReg = new RegExp('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$');
            //表单验证
            if(!this.intervalSeconds){
                this.showToast('请选择间隔时间','is-warning');
                return;
            }else if(!this.sleepInterval) {
                this.showToast('请选择休眠时间','is-warning');
                return;
            }else if(!this.continuousMailCount){
                this.showToast('请选择连续发件数','is-warning');
                return;
            }else if(!this.replyMailAd){
                this.showToast('请填写收件箱','is-warning');
                return;
            }else if(!emailReg.test(this.replyMailAd)){
                this.showToast('邮箱格式有误,请重新填写','is-warning');
                return;
            }else if(!this.radio){
                this.showToast('请选择发件箱','is-warning');
                return;
            }else if(!this.currentCustomerType){
                this.showToast('请选择发件客户分类','is-warning');
                return;
            }
            var tempArr=[]
            for(var i=0;i<this.templateList.length;i++){
              if(this.templateList[i].status=="accepted"){
                tempArr.push(this.templateList[i].id)
              }
            }
            if(tempArr.length==0 && (!this.content ||!this.mailTitle)){
              if(!this.content){
                this.showToast('请填写邮件内容','is-warning');
                return;
               }else if(!this.mailTitle){
                this.showToast('请填写邮件主题','is-warning');
                return;
               }
            }
            var realContent=this.content+"<br><br>"+this.sign
            tempArr=JSON.stringify(tempArr)
            this.isLoading = true;
            let emailDTO = {
                subjects: [this.mailTitle],
                fromMailId: [this.radio],
                replyTo: this.replyMailAd,
                intervalInSeconds: this.intervalSeconds,
                sleepInterval: this.sleepInterval,
                content: realContent,
                sleepEveryNLetters: this.continuousMailCount,
                customerTypeId: this.currentCustomerType,
                template:tempArr,
            };
            startMailTask(this.userId,emailDTO).then(res => {
                this.isLoading = false;
                this.$toast.open({
                    message: '发送成功',
                    type: 'is-success'
                })
            }).catch((e) => {
                this.isLoading = false;
                this.$toast.open({
                    message: e.message || '服务器错误',
                    type: 'is-danger'
                })
            })
        },
        // onEditorBlur(editor) {
        //     // console.log('editor blur!', editor)
        // },
        // onEditorFocus(editor) {
        //     // console.log('editor focus!', editor)
        // },
        // onEditorReady(editor) {
        //     // console.log('editor ready!', editor)
        // }
      confirmSaveMailTmp(){
        let tempName = this.tempName;
        let mailTitle = this.mailTitle;
        let mailContent = this.content;
        let mailSign = this.sign;
        if(tempName!='' && mailTitle!='' && mailContent!=''&& mailSign!=''){
          this.isLoading = true;
          createMaiTemp(this.userId,tempName,mailTitle,mailContent,mailSign).then((res) => {
            this.$toast.open({
              message: '保存邮件模板成功',
              type: 'is-success'
            })
            this.inputTmpNameActive = false;
            this.getTempList();
            this.isLoading = false;
          }).catch(e => {
            this.isLoading = false;
            this.$toast.open({
              message: e.message || '服务器未知错误',
              type: 'is-danger'
            })
          });
        }else {
          this.$toast.open({
            message: '请填写完整信息',
            type: 'is-danger'
          })
        }
      },
      confirmUpdateMailTmp(){
        let tempName = this.tempName;
        let mailTitle = this.mailTitle;
        let mailContent = this.content;
        let mailSign = this.sign;
        let tmpId = this.currentTmpId;
        if(tempName!='' && mailTitle!='' && mailContent!=''&& mailSign!=''){
          this.isLoading = true;
          updateMaiTemp(this.userId,tempName,mailTitle,mailContent,mailSign,tmpId).then((res) => {
            this.$toast.open({
              message: '更新邮件模板成功',
              type: 'is-success'
            })
            this.getTempList();
            this.isLoading = false;
          }).catch(e => {
            this.isLoading = false;
            this.$toast.open({
              message: e.message || '服务器未知错误',
              type: 'is-danger'
            })
          });
        }else if(tempName && tempName==0){
          this.$toast.open({
            message: '该模板无历史记录',
            type: 'is-danger'
          })
        }else {
          this.$toast.open({
            message: '请填写完整信息',
            type: 'is-danger'
          })
        }
      },
      async confirmDeleteMailTmp(tmpId) {
        this.$dialog.confirm({
          title: '删除模板',
          message: '确定要 <b>删除</b> 此模板? 数据删除后不可回复',
          confirmText: '确定删除',
          cancelText: '取消',
          type: 'is-danger',
          hasIcon: false,
          onConfirm: () => {
          this.isLoading = true;
          deleteUserMailTemp(this.userId,tmpId).then((res) => {
            this.$toast.open({
              message: '删除邮件模板成功',
              type: 'is-success'
            })
            this.getTempList();
            this.isLoading = false;
          }).catch(e => {
            this.isLoading = false;
            this.$toast.open({
              message: e.message || '服务器未知错误',
              type: 'is-danger'
            })
          });
          }
        })
      },
      //新建发件箱
      createNewMailBox(){
        let email = this.email;
        let password = this.password;
        let sendBoxType = this.sendBoxType;
        if(email && password && (sendBoxType != '-1')){
          this.isLoading = true;
          createUserMailBox(this.userId,email,password,sendBoxType).then((res) => {
            this.$toast.open({
              message: '新建发件箱成功',
              type: 'is-success'
            })
            this.isNewMailCardActive = false;
            this.email="";
            this.password="";
            this.sendBoxType="";
            this.getSendBoxList();
            this.isLoading = false;
          }).catch(e => {
            this.isLoading = false;
            this.$toast.open({
              message: e.message || '服务器未知错误',
              type: 'is-danger'
            })
          });
        }else {
          this.$toast.open({
            message: '请填写完整信息',
            type: 'is-danger'
          })
        }
      },
      //删除发件箱
      async deleteSendMailBox(mailBoxId) {
        this.$dialog.confirm({
          title: '删除发件箱',
          message: '确定要 <b>删除</b> 此邮箱? 数据删除后不可回复',
          confirmText: '确定删除',
          cancelText: '取消',
          type: 'is-danger',
          hasIcon: false,
          onConfirm: () => {
            this.isLoading = true;
            deleteUserMailBox(this.userId,mailBoxId).then((res) => {
              this.$toast.open({
                message: '删除成功',
                type: 'is-success'
              })
              this.getSendBoxList();
              this.isLoading = false;
            }).catch(e => {
              this.isLoading = false;
              this.$toast.open({
                message: e.message || '服务器未知错误',
                type: 'is-danger'
              })
            })
          }
        })
      },
      openTmpDetail(row){
        this.tempName=row.tempName
        this.currentTmpId=row.id
        this.mailTitle=row.mailTitle
        this.content=row.mailContent
        this.sign=row.mailSign
      }
    },
}
</script>
<style>
  .quill-editor:not(.bubble) .ql-container,
  .quill-editor:not(.bubble) .ql-container .ql-editor {
    height: 20rem;
    padding-bottom: 1rem;
  }
</style>
<style lang="less" scoped>
.modal-table {
    background-color: #ffffff;
    padding: 30px 20px;
    text-align: center;
}
.edit-container {
  margin: 30px 20px;
  padding: 40px 40px;
  min-height: 80vh;
  background-color: #ffffff;
    .mail-settings {
        .receive-settings {
            margin-top: 10px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            .button {
                margin-left: 10px;
            }
            .send-num {
                .left-margin;
            }
            .send-interval {
                .left-margin;
            }
            .input-item {
                margin-right: 10px;
            }
        }
    }
    // .mail-editor {
    //     min-height: 300px;
    // }
}
.left-margin {
    margin-left: 10px;
}
.settings {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    a {
        .left-margin;
    }
    .field {
        .left-margin;
    }
    .password {
        .left-margin;
    }
    .settings-left {
        display: flex;
    }
}
.mail-container {
    height: 100%;
    display: flex;
    // .mail-list {
    //     background-color: #ffffff;
    //     height: 100%;
    //     padding: 30px 10px;
    //     flex: 2;
    // }
    .mail-content {
        padding: 20px 10px;
        flex: 5;
        .mail-editor {
            border-radius: 5px;
            margin-top: 20px;
            background-color: #ffffff;
            padding: 30px 20px;
            // height: 50vh;
            box-shadow: 0 2px 24px 0 rgba(0,0,0,0.04);
            .mail-title {
                margin-top: 10px;
                margin-bottom: 10px;
            }
        }
        .settings {
            border-radius: 5px;
            background-color: #ffffff;
            padding: 30px 20px;
            box-shadow: 0 2px 24px 0 rgba(0,0,0,0.04);
        }
    }
}
</style>
